<template>
  <transition name="dialog">
    <div
      class="modal-wrapper"
      ref="dialogWrapperRef"
      v-show="visibleDialog"
      @click.self="handleWrapperClick"  
      @mousewheel.prevent.stop
    >
      <div
        ref="dialogRef"
        :class="['default-dialog']"
        v-show="visibleDialog"
        :style="{top:props.top}"
        @mousewheel.passive.stop
      >
        <!-- 对话框主体 -->
        <div class="modal-body" :style="{width:props.width?props.width:''}">
          <div class="title" v-show="props.showTop">
            <span>{{props.title}}</span>
            <div class="dialog-top thumb" @click="handleClose">
              <img v-lazy="publicUrl(`/images/dialog-close.png`)" />
            </div>
          </div>
          <!-- 默认插槽 -->
         <div :class="[scroll ? `modal-slot`:`` ]" >
            <slot></slot>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup lang="ts">
import { watch, ref } from "vue";
import { publicUrl } from "@/utils/util";


const dialogWrapperRef = ref<HTMLElement | null>(null);
const dialogRef = ref<HTMLElement | null>(null);

// 采用定义props接口
interface Props {
  visible?: boolean;          //是否显示
  title?: string;             //弹出层标题
  scroll?:boolean;            //是否超出滚动
  beforeClose?: () => {};     //关前回调
  modal?: boolean;            //是否显示背景模态
  showTop?:boolean;           //是否显示头部
  // 最大宽高
  width?: string;             //弹出层宽度
  height?: string;            //高度
  top?: string;               //距离顶部位置
}

// 采用ts专有声明，有默认值
const props = withDefaults(defineProps<Props>(), {
  visible: false,
  showTop:true,
  title: "",
  scroll:true, 
  modal: true,
  top: "20vh",
});
const visibleDialog = ref(props.visible);
// 解构props
const {
  beforeClose,
} = props;

// 定义emit方法名称
const emit = defineEmits(["close", "open", "update:visible"]);

// 监听visible改变
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      visibleDialog.value = true;
      // 依据props修改样式
      emit("open");
    } else {
      visibleDialog.value = false;
      emit("close");
    }
  }
);


// 处理关闭对话框，若存在beforeClose则调用
const handleClose = () => {
  if (typeof beforeClose === "function") {
    beforeClose();
    updateVisible();
  } else {
    updateVisible();
  }
};
const handleWrapperClick = () => {
  if (typeof beforeClose === "function") {
    beforeClose();
    updateVisible();
  } else {
    updateVisible();
  }
};
// 通知更新visible = false
const updateVisible = () => {
  emit("update:visible", false);
};

// 根据Props值修改Dialog样式
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
